package com.google.devrel.example.android.protips.mvp;

import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.SensorManager;
import android.view.Display;
import android.view.WindowManager;

import com.google.devrel.example.android.protips.mvp.IMainView.AccOrientationSensorListener;
import com.google.devrel.example.android.protips.mvp.IMainView.GyroOrientationSensorListener;

public class MainPresenter {

	private IMainView _view;
	private Context _context;

	public MainPresenter(IMainView view) {
		_view = view;
		if (view instanceof Context)
			_context = (Context) view;
	}

	private static boolean newSensorApiSupported = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.CUPCAKE;
	private IOrientationSensorListener orientationSensor;

	public void setupSensor() {
		if (orientationSensor == null) {
			orientationSensor = findBestOrientationSensorListener();
			orientationSensor
					.setOrientationChangeListener(new OrientationChangeListener() {

						@Override
						public void onOrientationChanged(String side) {

							Display display = ((WindowManager) _context.getSystemService(Context.WINDOW_SERVICE))
									.getDefaultDisplay();

							_view.setOrientationText(
									"" + display.getOrientation(),
									orientationSensor.getType() + " - " + side);
						}

					});
		}
	}

	public void clearSensors() {
		if (orientationSensor != null) {
			orientationSensor.removeAllListeners();
		}
	}

	protected IOrientationSensorListener findBestOrientationSensorListener() {
		boolean gyroExists = _context.getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_SENSOR_GYROSCOPE);

		SensorManager man = (SensorManager) _context.getSystemService(Context.SENSOR_SERVICE);

		if (gyroExists) {
			return new GyroOrientationSensorListener(man);
		} else if (newSensorApiSupported) {
			return new AccOrientationSensorListener(man);
		}
		return null;
	}
}
